package com.xiaouyudeguang.common.dirule.service.impl;

import com.xiaouyudeguang.common.annotation.ApiService;
import com.xiaouyudeguang.common.cache.RedisCache;
import com.xiaouyudeguang.common.dirule.dao.DiRuleDao;
import com.xiaouyudeguang.common.dirule.entity.DiRule;
import com.xiaouyudeguang.common.dirule.service.DiRuleService;
import com.xiaouyudeguang.common.service.impl.AbstractServiceImpl;
import org.springframework.beans.factory.annotation.Value;

import java.util.concurrent.TimeUnit;

import static com.xiaouyudeguang.common.config.MybatisPlusConfig.TABLE_NAME;

@ApiService
public class DiRuleServiceImpl extends AbstractServiceImpl<DiRuleDao, DiRule> implements DiRuleService {

    @Value("${api.cache.enabled:false}")
    private boolean isCache;

    @Override
    public DiRule getRule(String tenantId, String appId, String version, String tableName, String methodName) throws Exception {
        String ruleId = tableName + ":" + methodName;
        DiRule diRule = RedisCache.get("rules:" + ruleId, DiRule.class);
        if (!isCache || diRule == null) {
            diRule = getOne(lambdaWrapper().eq(DiRule::getRuleId, ruleId).eq(DiRule::getVersion, version));
            if (diRule == null) {
                diRule = getOne(lambdaWrapper().eq(DiRule::getGroupId, tableName).eq(DiRule::getVersion, version));
            }
            if (diRule != null) {
                RedisCache.set("rules:" + ruleId, diRule, diRule.getCacheTime(), TimeUnit.MINUTES);
            }
            TABLE_NAME.remove();
        }
        return diRule;
    }
}
